<?php

namespace App\Action\Service;

use Forxx\RedisCache;
use Forxx\ForxxWebService;
use \Lavender\Filter;

class sse_service extends ForxxWebService
{
    protected $without_auth_actions = ['*'];
    protected $without_sign_actions = ['*'];


    public function consume_action()
    {
        @set_time_limit(0);
        $params = $this->parameters([
            'token' => Filter::T_STRING,
        ],self::M_GET,true);
        $token = $params['token'];
        $start = time();
        $resp = [];
        $key = "sse_".$token;
        while(true){
            $tn = time();
            if($tn - $start > 1800){ // 半小时 重置一次
                break;
            }
            $data = RedisCache::instance()->lpop($key);
            if(!empty($data)){
                $resp = @json_decode($data,true);
                break;
                //echo "data: ".$data."\n\n";
            }
            else{
                sleep(1);
            }
        }
        return $this->success('ok',$resp);
    }

    public function publish_action()
    {
        $token = $_GET['token'];
        $key = "sse_".$token;
        $data = file_get_contents("php://input");
        RedisCache::instance()->rpush($key,$data);
        return $this->success('ok');
    }
}
